package ar.edu.utn.frgp.banco.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.utn.frgp.banco.domain.Cliente;
import ar.edu.utn.frgp.banco.exceptions.PersonalisedException;
import ar.edu.utn.frgp.banco.service.GestionUsuariosService;
import ar.edu.utn.frgp.banco.service.impl.GestionUsuariosServiceImpl;

/**
 * Servlet implementation class Login
 */
public class Login extends SuperServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1967138402507321464L;
	private static GestionUsuariosService gestion;
	
	private Cliente cliente;
	
	
	public Login(){
		if (gestion == null) gestion = new GestionUsuariosServiceImpl();
	}
	
     
	@Override
    public String execute(HttpServletRequest req, HttpServletResponse resp)
    		throws ServletException, IOException,Exception {
    	
		if (req.getParameter("logOut") != null){
			req.getSession().invalidate();
			return "/exc/login.jsp";
		}
		Cliente cliente = new Cliente();
		
		if (req.getParameter("dni") != null){
			cliente.setDni(req.getParameter("dni"));
		} else {
			if (req.getParameter("password") == null) {
				if (!req.getSession().isNew()){
					
				}
			}
		}
		
		if (req.getParameter("password") != null){
			cliente.setClave(req.getParameter("password"));
		}
		try{
			cliente = gestion.hacerLogIn(cliente);
		} catch (PersonalisedException e){
			addError(e.getError());
			return "/exc/login.jsp";
		}
		
		clienteActivo = cliente;
		
		if (cliente.isLogOk()){
			if (clienteActivo != null){
				this.recargarCuentas();
				this.recargarPrestamos();
			}
			
			return "/app/welcome.jsp";
		} else {
			addError("usuario o clave incorrecta.");
			return "/exc/login.jsp";
		}
		
		
    	
    }


	@Override
	public boolean populate(HttpServletRequest req) {
		
		cliente = new Cliente();
		
		cliente.setDni(req.getParameter("dni"));
		cliente.setClave(req.getParameter("clave"));
		
		return true;
	}

}
